define(function(require,exports){
    var common = require("common");
    var validate = require("validate");
    var template = require("template");
    var jArea = require("jArea");
    //require('ajaxFileUpload');


    /**
     * 上传文件入口
     * @param $obj
     * 上传文件,pid为父区域ID,为方便同一页面多处使用
     */
    var uploadFile=function($obj){
        require.async("ajaxFileUpload",function(ajaxFileUpload){
            $obj.on("change",'.fileBar',function(){
            //上传文件后缀名检测
            var $self=$(this);
            if(!common.testFile($self,"png|jqeg|jpg|gif|bmp")){
                return false;
            }
            var fileId = $obj.find(".fileBar")[0].id;
            $.ajaxFileUpload({
                url:'/utils/Upload/upload?fileInputName=src&t=' + (new Date()).getTime(),//用于文件上传的服务器端请求地址
                secureuri:false,//一般设置为false
                fileElementId:fileId,//文件上传空间的id属性  <input type="file" id="file" name="file" />
                dataType: 'json',//返回值类型 一般设置为json
                success: function (item, status){
                    if(item.code !== "000"){
                        layer.alert('<p class="cRed">'+item.message+'</p>',{title:"温馨提示",icon:0});
                        return;
                    }
                    $obj.find('[data-id="imgInput"]').val(item.message);
                    //图片显示
                    $obj.find(".img").html('<img src="'+item.message+'" />');
                    $obj.addClass("active");
                    /*$obj.find(".fileUpload").hide();
                    $obj.find(".uploaded").show();*/
                    //移除错误信息
                    $obj.find("label.error").remove();
                },
                error: function (data, status, e){
                    layer.alert('<p class="cRed">上传失败，错误信息：'+e+'</p>',{title:"温馨提示",icon:2});
                }
            });
        });
        });
    };
    /**
     * 重新上传
     * @param $form 表单对象
     */
    var reUpload=function($form){
        $form.on("click",'[data-act="reUpload"]',function(){
            //TODO:删除对应图片
            var $wrap=$(this).closest(".fileWrap");
            var imgPath =  $wrap.find('[data-id="imgInput"]').val();
            layer.msg('<div class="msg_success">移除成功！</div>',{shade:0.1},function(){
                $wrap.find('[data-id="imgInput"]').val("");
                $wrap.removeClass("active");
               /* $wrap.find(".uploaded").hide();
                $wrap.find(".fileUpload").show();*/
            });
            /*common.ajaxHandle({
                url: '/utils/Upload/delete',
                data:{imgPath: imgPath},
                callback:function(){
                    layer.msg('<div class="msg_success">删除成功！</div>',{shade:0.1},function(){
                        $wrap.find('[data-id="imgInput"]').val("");
                        $wrap.find(".uploaded").hide();
                        $wrap.find(".fileUpload").show();
                    });
                }
            });*/

        });
    };

    //放大图片
    $('[data-act="zoom"]').on('click',function(){
        var src= $(this).next().children("img")[0].src;
        var height = $(window).height()*0.5+'px';
        var width = $(window).width()*0.5+'px';
        var img = '<img src="'+ src+'" style="width: '+width+';height'+height+'">';
        layer.open({
            type: 1,
            title: false,
            area: [500,400],
            shadeClose: true,
            content:img
        })
    });
    $('[data-act="big"]').on('click',function(){
        var src= $(this).children("img")[0].src;
        var height = $(window).height()*0.5+'px';
        var width = $(window).width()*0.5+'px';
        var img = '<img src="'+ src+'" style="width: '+width+';height'+height+'">';
        layer.open({
            type: 1,
            title: false,
            area: [500,400],
            shadeClose: true,
            content:img
        })
    });

    //资质认证1··   初始化操作
    exports.aptitudeInit = function() {
        $(".area-wrap").JAreaSelect(exports.area);
        common.leftNav({dl:3,dd:1});

        var $form = $("#form1");
        $form.find('.fileWrap').each(function(){
            uploadFile($(this));
        });
        reUpload($form);

        $form.validate({
            ignore: ".ignore",
            rules: {
                "data[company]": {maxlength:20,required: true},
                "data[address]":{maxlength:20},
                "data[register_capital]":{number:true},
                "data[zipcode]":{isZipCode:true},
                "data[type]":{required: true},
                "main_business[]":{required: true},
                "data[legal_person]":{required:true, maxlength:20},
                "data[mobile]": {required: true,isMobile:[true]},
                "data[idcard_no]": {required: true, cretID:[true]},
                "data[idcard_positive]": {required: true},
                "data[idcard_opposite]": {required: true},
                "data[license]": {required: true, maxlength:20},
                "data[license_pic]":{required: true},
                "data[taxno]": {required: true, maxlength:20},
                "data[taxno_pic]": {required: true},
                "data[orgcode]": {required: true, maxlength:20},
                "data[orgcode_pic]": {required: true}
            },
            messages: {
                "data[company]":{required:"请填写公司名称"},

                "data[type]":{required:"请选择企业类别"},
                "main_business[]":{required:"请选择主营行业"},
                "data[legal_person]":{required:"请填写法定代表"},
                "data[mobile]":{required:"请填写法定代表人手机"},
                "data[idcard_no]": {required: "请填写法人身份证"},
                "data[idcard_positive]": {required: "请上传图片"},
                "data[idcard_opposite]": {required: "请上传图片"},
                "data[license]": {required: "请填写营业执照"},
                "data[license_pic]": {required: "请上传图片"},
                "data[taxno]": {required: "请填写税务登记号"},
                "data[taxno_pic]": {required: "请上传图片"},
                "data[orgcode]": {required: "请填写组织机构代码"},
                "data[orgcode_pic]": {required: "请上传图片"}
            },
            errorPlacement:function(place,$ele) {
                $ele.parent().append(place);
            },
            submitHandler: function (form) {
                common.ajaxHandle({
                    url:"do_aptitude",
                    data:$form.serialize()
                });
            }
        });

       

        $('.radio-aptitude input').on("change",function(){
            
            var a=$(this).val();
            if(a==1&&$(this).prop("checked")){
                $('.row_none').hide().find("input").prop("disabled",true);
            }else{
                $('.row_none').show().find("input").prop("disabled",false);
            }
        }).change();


    };

    //实名认证下的大塑注册页面
    exports.regInit = function() {
        common.leftNav(exports.leftNavIndex);
        var $form = $("#form1");
        var $getCodeBtn = $('[data-act="getSMS"]');
        var $mobile = $('input[name="data[phone]"]');
        common.getCode($getCodeBtn,4,$mobile);

        //图片重新上传
        reUpload($form);
        $form.validate({
            rules: {
                "data[phone]": {
                    required: true,
                    isMobile:[true]
                },
                "vcode": {
                    required: true,
                    maxlength:20
                },
                "data[password]": {
                    required: true,
                    pwd:[true],
                    maxlength:20
                },
                "data[sure_pwd]": {
                    required: true,
                    equalTo: "#pwd",
                    maxlength:20
                },

                "data[name]": {
                    required: true,
                    maxlength:20
                }
            },
            messages: {
                "data[phone]": {
                    required: "请填写手机号码"
                },
                "vcode": {
                    required: "请填写验证码"
                },
                "data[password]": {
                    required: "请填写登陆密码"
                },
                "data[sure_pwd]": {
                    required: "请填写确认密码",
                    equalTo: "密码不一致"
                },
                "data[name]": {
                    required: "请填写联系人"
                }
            },
            success: function (label, element) {
                $(element).parent().removeClass("error");
                var elementName = element.getAttribute('name'),
                    inValid = element.getAttribute('aria-invalid');
                if(elementName == 'data[phone]' && inValid == 'false'){
                    $getCodeBtn.data("active",true).addClass('active').prop("disabled",false);
                }
            },
            highlight: function (element, errorClass) {
                $(element).parent().addClass(errorClass);
                var elementName = element.getAttribute('name'),
                    inValid = element.getAttribute('aria-invalid');
                if(elementName == 'data[phone]' && inValid == 'true'){
                    $getCodeBtn.data("active",true).removeClass('active').prop("disabled",true);
                }
            },
            submitHandler: function (form) {
                //console.log(111);
                //return false;
                //form.submit();
                common.ajaxHandle({
                    url: "/member/member/do_register",
                    data: $form.serialize()
                })
            }
        });
    };


    //个人基本信息初始化操作
    exports.indexInit = function() {
     
        common.leftNav({dl:3 ,dd:0});
        //手机修改按钮及表单验证
        $('[data-act="phone_amend"]').on("click",function(){
            var html = template("phoneValid",{});
            layer.open({
                content:html,
                btn:["确定","取消"],
                title:["手机号码修改"],
                area: ['600px'],
                success:function(layero,index){
                    var $form = layero.find("form");
                    var $getCodeBtn = $('[data-act="getSMS"]');
                    var $mobile = $('#mobile');
                    common.getCode($getCodeBtn,1,$mobile);

                    $form.validate({
                        ignore: ".ignore",
                        rules:{
                            password:{required: true},
                            username:{required: true,isMobile:true},
                            vcode:{required: true}
                        },
                        messages:{
                            password:{required: "请输入登陆密码"},
                            username:{required: "请输入新的手机号码"},
                            vcode:{required:"请输入验证码"}
                        },
                        success: function (label, element) {
                            $(element).parent().removeClass("error");
                            var elementName = element.getAttribute('name'),
                                inValid = element.getAttribute('aria-invalid');
                            if(elementName == 'username' && inValid == 'false'){
                                $getCodeBtn.data("active",true).addClass('active').prop("disabled",false);
                            }
                        },
                        highlight: function (element, errorClass) {
                            $(element).parent().addClass(errorClass);
                            var elementName = element.getAttribute('name'),
                                inValid = element.getAttribute('aria-invalid');
                            if(elementName == 'username' && inValid == 'true'){
                                $getCodeBtn.data("active",true).removeClass('active').prop("disabled",true);
                            }
                        },
                       submitHandler:function(f){
                          common.ajaxHandle({
                            url:"/member/member/do_modifyMobile",
                            data:$form.serialize(),
                            errorback:function(data) {
                                var msg = data.message;
                                if(msg.indexOf("手机")!=-1) {
                                    $("#mobile").val("").addClass("error").focus();
                                    var tip ='<label id="mobile-error" class="error" for="mobile">'+msg+'</label>';
                                    $("#mobile").parent().append(tip);
                                }else if(msg.indexOf("密码")!=-1){
                                    $("#pwd").val("").addClass("error").focus();
                                    var tip ='<label id="pwd-error" class="error" for="pwd">'+msg+'</label>';
                                    $("#pwd").parent().append(tip);
                                }else if(msg.indexOf("验证码")!=-1){
                                    $("#vcode").val("").addClass("error").focus();
                                    var tip ='<label id="vcode-error" class="error" for="vcode">'+msg+'</label>';
                                    $("#vcode").parent().append(tip);
                                }else {
                                    common.error(msg);
                                }

                            }
                        });
                       }
                    });
                },
                yes:function(index,layero){
                    var $form = layero.find("form");
                    $form.submit();
                }
            })
        });

        //基本信息表单验证以及图片上传
        var $form = $("#form1");
        $form.find('.fileWrap').each(function(){
            uploadFile($(this));
        });
        reUpload($form);
        $form.validate({
            submitHandler: function (form) {
                common.ajaxHandle({
                    url: "/member/member/do_edit",
                    data: $form.serialize()
                })
            }
        });
    };

    /*个人信息页面-收货地址-表单验证*/
    exports.addrInit = function(json){
        $(".area-wrap").JAreaSelect(json);
        common.leftNav(exports.leftNavIndex);
        var $form = $("#form1");
        $form.validate({
            rules: {
                "data[address]": {
                    required: true
                    ,maxlength:20
                },
                "data[zip_code]": {
                    maxlength:6
                },
                "data[consignee]": {
                    required: true
                    ,maxlength:20
                },
                "data[contact_mobile]": {
                    required: true,
                    isMobile:true
                },
                "data[telephone]": {isTel: true}
            },
            messages: {

                "data[address]": {
                    required: "请填写详细地址"
                },
               
                "data[consignee]": {
                    required: "请填写收货人姓名"
                },
                "data[contact_mobile]": {
                    required: "请填写手机"

                }

            },
            submitHandler: function (form) {
                common.ajaxHandle({
                    url: form.action,
                    data: $form.serialize()
                })
            }
        });

        /*删除收货地址*/
        $("[data-act='do_delete']").on("click",function(){
            var id= $(this).data('id');
            layer.confirm("是否要删除该条记录？",{
                btn:["确定","取消"]
            },function () {
                layer.load();
                $.post("do_delete",{id:id},function(data){
                    layer.closeAll('loading');
                    if(data.code == '000' || data.code=='success'){
                        layer.msg("操作成功");
                        document.location.reload();
                    }else{
                        layer.msg(data.message);
                    }
                });
            })
        });
        //设置默认收货地址
        $("[data-act='de_setDefault']").on("click",function(){
            var id= $(this).data('id');
            common.ajaxHandle({
                url:"setDefault",
                data:{"id":id}
            });
        });
    };

    //绑定大塑支付
    exports.boundPay = function() {
        common.leftNav({dl:3 ,dd:1});
        $('[data-act="bount"]').on("click",function(){
            var html = template("bountValid",{});
            layer.open({
                content:html,
                btn:["确定","取消"],
                title:["大塑账户绑定"],
                area: ['520px'],
                success:function(layero,index){
                    var $form = layero.find("form");
                    $form.validate({
                        ignore: ".ignore",
                        rules:{
                            password:{required: true,pwd:[true]},
                            username:{required: true}
                        },
                        messages:{
                            password:{required: "请输入密码"},
                            username:{required: "请输入大塑账户"}
                        },
                        submitHandler:function(f){
                            common.ajaxHandle({
                                url:"do_bind",
                                data:$form.serialize()
                            });
                        }
                    });
                },
                yes:function(index,layero){
                    var $form = layero.find("form");
                    $form.submit();
                }

            })
        });
    };

    //账户安全初始化
    exports.saveInit = function() {
        common.leftNav({dl:3 ,dd:3});
        //账户安全页面-登陆密码-修改按钮
        $('[data-act="login_pass"]').on("click",function(){
            var html = template("loginValid",{});
            layer.open({
                content:html,
                btn:["确定","取消"],
                title:"登录密码修改",
                area:['500px'],
                success:function(layero,index){
                    var $form = layero.find("form");
                    $form.validate({
                        ignore: ".ignore",
                        rules:{
                            old_pwd:{required: true},
                            new_pwd:{required: true,pwd:[true],notEqualTo:'#oldPwd'},
                            sure_pwd:{required: true,equalTo:".new_pwd"}
                        },
                        messages:{
                            old_pwd:{required: "请输入原密码"},
                            new_pwd:{required: "请输入新密码",notEqualTo:"新密码不能与旧密码相同"},
                            sure_pwd:{required: "请确认密码"}
                        },
                        submitHandler:function(f){
                            common.ajaxHandle({
                                url:"do_modifyPassword",
                                data:$form.serialize(),
                                errorback:function(data) {
                                    $("#oldPwd").val("").addClass("error").focus();
                                    var tip ='<label id="oldPwd-error" class="error" for="oldPwd">'+data.message+'</label>';
                                    $(".old_pwd_wrap").append(tip);
                                }
                            });
                        }
                    });
                },
                yes:function(index,layero){
                    var $form = layero.find("form");
                    $form.submit();
                }
            })
        });

        //账户安全页面-交易密码-设置按钮和修改按钮
        $('[data-act="deal_pass"]').on("click",function(){

            var html = template("dealValid",{});
            layer.open({
                type:1,
                content:html,
                btn:["确定","取消"],
                title:["更改交易密码"],
                area:['600px'],
                success:function(layero,index){
                    var $form = layero.find("form");
                    //获取验证码
                    var $getBtn = $('[data-act="getSMS"]');
                    var $mobile = $('#username');
                    common.getCode($getBtn,3,null);

                    $form.validate({
                        ignore: ".ignore",
                        rules:{
                            password:{required: true,sixPwd:true},
                            sure_pwd:{required: true,equalTo:"#pwd"},
                            vcode:{required: true}
                        },
                        messages:{
                            password:{required: "请输入密码"},
                            sure_pwd:{required: "请确认密码",equalTo:"两次密码不一致"},
                            vcode:{required: "请输入手机验证码"}
                        },
                        submitHandler:function(f){
                            common.ajaxHandle({
                                url:"do_tradePass",
                                data:$form.serialize()
                            });

                        }
                    });
                },
                yes:function(index,layero){
                    var $form = layero.find("form");
                    $form.submit();
                }
            })
        });
    }

});
